//渲染我的信息
async function render() {
  const user_id = localStorage.getItem("user_id");
  const res = await axios({
    url: "/renderProfile",
    params: {
      user_id
    }
  })
  const item = res.msg;
  if (res.code == 0) {
    document.querySelector(".space-x-6").innerHTML = `<div class="flex items-end space-x-6">
            <img src='http://127.0.0.1:3000${item.avatar_url}' alt="用户头像" class="w-32 h-32 rounded-full border-4 border-white shadow-lg">
            <div class="text-white pb-4">
              <h1 class="text-3xl font-bold">${item.nickname} <button>修改资料</button></h1>
              <p class="mt-2 text-lg opacity-90">${item.user_description}</p>
              <div class="flex items-center space-x-6 mt-4">
                <span>关注 128</span>
                <span>粉丝 3.2k</span>
                <span>获赞 ${item.total_poem_likes}</span>
              </div>
            </div>
          </div>`
  }
  const bjzl = document.querySelector(".bjzl");
  const bjzlImg = bjzl.querySelector("img");
  let aa
  bjzl.querySelector("label").addEventListener("change", async e => {
    aa = e.target.files[0];
    bjzlImg.src = URL.createObjectURL(e.target.files[0]);
  })
  const submitButton = document.querySelector("#tj");
  submitButton.addEventListener("click", async e => {
    e.preventDefault()
    const fd = new FormData();
    fd.append("file", aa);
    fd.append("user_id", user_id);
    fd.append("nickname", bjzl.querySelector("input[type='text']").value);
    fd.append("user_description", bjzl.querySelector("textarea").value);
    const res = await axios({
      url: "/updateUser",
      method: 'POST',
      data: fd
    })
    bjzl.style.display = "none"
    if (res.code == 0) {
      res.msg && localStorage.setItem("url", res.msg);
      render();
    }
  })
  document.querySelector(".pb-4 button ").addEventListener("click", () => {
    bjzl.querySelector("input[type='text']").value = item.nickname
    bjzl.querySelector("textarea").value = item.user_description
    bjzl.querySelector("img").src = `http://127.0.0.1:3000${item.avatar_url}`;
    bjzl.style.display = "block";
    document.body.style.overflow = 'hidden';
  })
  document.querySelector(".bjzl i").addEventListener("click", () => {
    bjzl.style.display = "none";
    document.body.style.overflow = 'auto';
  })
}
render();

function addBrToText(text) {
  const pattern = /([，。！？\s])/g;
  return text.replace(pattern, '$1<br>');
}


//时间处理函数
function convertTimestampToLocalTime(timestamp) {
  const date = new Date(timestamp);
  const localYear = date.getFullYear();
  const localMonth = String(date.getMonth() + 1).padStart(2, '0');
  const localDay = String(date.getDate()).padStart(2, '0');
  const localHour = String(date.getHours()).padStart(2, '0');
  const localMinute = String(date.getMinutes()).padStart(2, '0');
  return `${localYear}-${localMonth}-${localDay} ${localHour}:${localMinute}`;
}

//渲染我的喜欢
const like = document.querySelector(".tab-content  .grid");
async function renderPoems() {
  const user_id = localStorage.getItem("user_id");
  const res = await axios({
    url: "/getLikedPoemsByUserId",
    params: {
      user_id
    }
  })
  console.log(res.msg);

  if (res.code == 0) {
    const str = res.msg.map(item => `<div  class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-start justify-between">
              <div>
                <h3 class="text-lg font-medium">${item.title}</h3>
                <p class="text-gray-500 mt-1">${item.nickname} ${item.user_id ? "(诗友)" : ""}</p>
              </div>
              <button data-id="${item.like_id}" class="text-primary"><i class="fas fa-heart"></i></button>
            </div>
            <p class="mt-4 text-gray-700">${addBrToText(item.content)}</p>
            <div class="mt-4 flex items-center text-sm text-gray-500">
              <span>${convertTimestampToLocalTime(item.like_time)} 收藏</span>
            </div>
          </div>`).join("")
    like.innerHTML = str;

    /* 取消点赞 */
    const buttons = like.querySelectorAll('button');
    buttons.forEach(button => {
      button.addEventListener('click', async () => {
        const buttonId = button.dataset.id;
        const res = await axios({
          url: "/deleteLikeById",
          method: 'delete',
          params: {
            like_id: buttonId
          }
        })
        if (res.code == 0) {
          myAlert(true, "取消成功")
          renderPoems();
          renderCreate();
        }
      });
    });
  }
}
renderPoems();

//渲染我的创作
const create = document.querySelector("#creations .grid");
async function renderCreate() {
  const user_id = localStorage.getItem("user_id");
  const res = await axios({
    url: "/renderCreate",
    params: {
      user_id: localStorage.getItem("user_id")
    }
  })
  if (res.code == 0) {
    const str = res.msg.map(item => `
          <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-start justify-between">
              <div>
                <h3 class="text-lg font-medium">${item.title}</h3>
                <p class="text-gray-500 mt-1">创作于 ${convertTimestampToLocalTime(item.created_at)}</p>
              </div>
              <div class="flex space-x-2">
                <button class="text-gray-400 hover:text-primary  edit-button"  data-id="${item.poem_id}"><i class="fas fa-edit"></i></button>
                <button class="text-gray-400 hover:text-red-500 delete-button" data-id="${item.poem_id}"><i class="fas fa-trash"></i></button>
              </div>
            </div>
            <p class="mt-4 text-gray-700">${addBrToText(item.content)}</p>
            <div class="mt-4 flex items-center justify-between text-sm text-gray-500">
              <span>点赞 ${item.likes_count}</span>
              <span>评论 ${item.comment_count}</span>
            </div>
          </div>`).join("")
    create.innerHTML = str;

    /* 删除按钮 */
    const deleteButtons = create.querySelectorAll('.delete-button');
    deleteButtons.forEach(button => {
      button.addEventListener('click', async () => {
        const btid = button.dataset.id;
        if (confirm("确定删除该作品吗？")) {
          const res = await axios({
            url: "/deletecrete",
            method: 'delete',
            params: {
              poem_id: btid
            }
          })
          if (res.code == 0) {
            myAlert(true, "删除成功")
            renderCreate();
          }
        }
      });
    });

    /* 编辑作品 */
    const bjzp = document.querySelector(".bjzp");
    const editButtons = create.querySelectorAll('.edit-button');
    const submitButton = document.querySelector("#xgzp");
    submitButton.addEventListener("click", async function (e) {
      e.preventDefault()
      const title = bjzp.querySelector("input[type='text']").value;
      const content = bjzp.querySelector("textarea").value;
      const poem_id = this.dataset.id;
      console.log(poem_id, title, content);

      const res = await axios({
        url: "/updatePoem",
        method: "post",
        data: {
          poem_id,
          title,
          content
        }

      })
      if (res.code == 0) {
        bjzp.style.display = "none";
        document.body.style.overflow = 'auto';
        renderCreate();
      }
    })

    editButtons.forEach(button => {
      button.addEventListener('click', async () => {
        const buttonId = button.dataset.id;
        submitButton.dataset.id = buttonId;
        const res = await axios({
          url: "/eidtPoem",
          params: {
            poem_id: buttonId
          }
        })
        if (res.code == 0) {
          console.log(res.msg);
        }
        bjzp.style.display = "block";
        document.body.style.overflow = 'hidden';
        bjzp.querySelector("input[type='text']").value = res.msg[0].title;
        bjzp.querySelector("textarea").value = res.msg[0].content;
      });
    });


    document.querySelector(".bjzp i").addEventListener("click", () => {
      bjzp.style.display = "none";
      document.body.style.overflow = 'auto';
    })
  }
}

renderCreate();
//tab切换
document.querySelectorAll('.tab-btn').forEach(button => {
  button.addEventListener('click', () => {
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.remove('text-primary', 'border-b-2', 'border-primary');
      btn.classList.add('text-gray-500');
    });
    button.classList.remove('text-gray-500');
    button.classList.add('text-primary', 'border-b-2', 'border-primary');

    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.remove('active');
    });
    document.getElementById(button.dataset.tab).classList.add('active');
  });
});
